Okar
Okar
文章目录
  1. 前言
  2. 概念
  3. 原理
  4. 使用
  5. Swift的Method Swizzling
  6. 注意点
  7. 参考资料

Runtime学习笔记2--Method Swizzling

前言

前文再续,书接上一回,我们知道了自己在开发的时候写的是“伪代码“执行的是另有其人后,就可以开始接触runtime的另一个黑魔法了,就是Method swizzling. 通俗点来讲,就是把自己写的一个方法在runtime执行阶段替换掉一个系统的方法,这符合了动态语言的特性,是runtime的用法的延伸。同时,我们可以利用苹果这一特性来实现AOP(面向切面编程)。

概念

Mattt Thompson 在 Method Swizzling 一文中写道:

Method swizzling is the process of changing the implementation of an existing selector. It’s a technique made possible by the fact that method invocations in Objective-C can be changed at runtime, by changing how selectors are mapped to underlying functions in a class’s dispatch table.

因为Objective-C是运行时语言,也就是说究竟会调用何种方法要在运行期才能解析出来。那么我们其实也可以在运行时改变选择子名称。这样我们既不需要查看到源代码,又没有必要去重写子类来覆写方法就能改变类本身的功能。这样一来新功能就会在类的所有实例中表现出来,而不仅限于那些重写子类的实例。这种方案就叫做“方法调配”(method swizzling)。

原理

我们先来了解下 Objective-C 中方法 Method 的数据结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
typedef struct method_t *Method;
struct method_t {
SEL name;
const char *types;
IMP imp;
struct SortBySELAddress :
public std::binary_function<const method_t&,
const method_t&, bool>
{
bool operator() (const method_t& lhs,
const method_t& rhs)
{ return lhs.name < rhs.name; }
};
};

我们可以看到,Method就是 struct methodt 类型的指针,所以我们重点看下结构体 methodt 的定义。在结构体 method_t 中定义了三个成员变量和一个成员函数:

  • name 表示的是方法的名称,用于唯一标识某个方法,比如 @selector(viewWillAppear:) ;
  • types 表示的是方法的返回值和参数类型(详细信息可以查阅苹果官方文档中的 Type Encodings);
  • imp是一个函数指针,指向方法的实现;
  • SortBySELAddress 顾名思义,是一个根据 name 的地址对方法进行排序的函数。

理论上,方法名称name与imp是一一对应的,而 Method Swizzling 的原理就是动态地改变它们的对应关系,以达到替换方法实现的目的。

二图以蔽之(也是盗图):
正常的函数调用:
正常的函数调用

Method Swizzling:
这里写图片描述

看完估计就很清晰了。

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#import "UIViewController+Swizzling.h"
#import <objc/runtime.h>
@implementation UIViewController (Swizzling)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(viewDidAppear:);
SEL swizzledSelector = @selector(swizzledViewDidAppear:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddedMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
NSLog(@"%@",didAddedMethod?@"YES":@"NO");
if (didAddedMethod) {
class_replaceMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
}else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
- (void)swizzledViewDidAppear:(BOOL)animated {
[self swizzledViewDidAppear:animated];
NSLog(@"View Controller: %@ did appear animated: %@", NSStringFromClass([self class]), animated?@"YES":@"NO");
}
@end

从代码中我们可以看到,我们在runtime时调用了的class_replaceMethod() 将我们自己写swizzledViewDidAppear()替换了UIViewController的原生方法viewDidAppear(),我们可以利用这一特性,在不影响viewDidAppear()代码的情况下添加一些我们需要的function。
此处推荐一个关于Method Swizzling的第三方库Aspects ,这是一个封装好的AOP库。 使用Demo在此DEMO

Swift的Method Swizzling

我们在谈论Method Swizzling的时候都是建立在Objective-C的基础上的,但是随着Swift的普及,我们在使用Swift开发的时候有些时候也会用到这个特性。在什么场景下,Swift可以用Method Swizzling呢?这里有两个必要条件:

  1. 包含 Swizzle 方法的类需要继承自 NSObject
  2. 需要 Swizzle 的方法必须有动态属性(dynamic attribute)

以上面例子为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import UIKit
extension UIViewController {
override public static func initialize() {
struct Static {
static var token: dispatch_once_t = 0;
}
dispatch_once(&Static.token) {
let originalSelector = Selector("viewDidAppear:")
let swizzledSelector = Selector("swizzledViewDidAppear:")
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didAddMethod:Bool = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
}else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
func swizzledViewDidAppear(animated: Bool) {
self.swizzledViewDidAppear(animated)
print("View Controller: \(self) did appear animated: \(animated)")
}
}

Compare to the code we can see that:

  1. in Objective-C we need import <objc/runtime.h>, but in Swift no need.
  2. in Objective-C Swizzling is call in - (void)load; , in Swift it’s call in func initialize().

注意点

  1. 因为 Swizzling 会改变全局状态,所以我们需要在运行时采取一些预防措施。GCD 的dispatch_once 可以保证操作的原子性,确保代码只被执行一次,不管有多少个线程。
  2. 有利也有弊,在 runtime 执行这类更改时,你就不能在编译时利用那些可用的安全检查了。因此,应该小心使用 Method Swizzling。

参考资料

Runtime系列2–Method Swizzling
Method Swizzling
Swift & the Objective-C Runtime
How to use MethodSwizzling in Swift in high performance

支持一下
扫一扫,支持Okar